//
//  EmoticonsView.swift
//  表情键盘的实现
//
//  Created by 李进 on 15/10/23.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit

let collectionViewID = "collectionViewID"

class EmoticonsView: UIView {
    
    private var selectedEmoticonCallBack: (emoticon: EmoticonsModel)->()
    
     let arrayModel = ViewModelManage.shareManage
    
    init(selectedEmoticon:(emoticon: EmoticonsModel)->()){
        
        //记录闭包属性
        selectedEmoticonCallBack  = selectedEmoticon
        
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.height = 226
        
        super.init(frame: rect)
        
        //设置 ui
        setupUI()
        
        //默认是滚动到第一页
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        
        expressionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //测试模拟数据分组
    
    
    //懒加载控件属性(查看表情键盘知道，键盘的组成是用一个toolbar和一个collectionview来组成)
    //collview表情显示区
    private lazy var expressionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EoticonsLayout())
    //表情分组组标题显示区
    private lazy var groupTollBar: UIToolbar = UIToolbar()
    
    /// 重写 layout 的布局方法
    private class EoticonsLayout: UICollectionViewFlowLayout{
    /// 这个方法当第一次创建 collView 的时候就会调用这个方法
        override private func prepareLayout() {
            super.prepareLayout()
            
            //行数
            let lineCount = 3
            //一行的个数
            let itemCount = 7
            
            let w = collectionView!.bounds.width / CGFloat(itemCount)
            
            let h = collectionView!.bounds.height / CGFloat(lineCount)
            
            itemSize = CGSize(width: w, height: h)
            
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}

// MARK: - 设置 view 的界面布局
extension EmoticonsView{
    //设置view的ui以及布局
    func setupUI(){
        
        
        
        expressionView.backgroundColor = UIColor.whiteColor()
        //添加控件
        addSubview(expressionView)
        
        addSubview(groupTollBar)
        
        let w = UIScreen.mainScreen().bounds.width
        
        let h = self.bounds.height
        
        //设置布局
        expressionView.frame = CGRectMake(0, 0, w, (4 / 5) * h)
        
        groupTollBar.frame = CGRectMake(0, CGRectGetMaxY(expressionView.frame), w, (1 / 5) * h)
        
        //设置 toolbar 界面
        createToolBarItem()
        
    }
    
    //创建tollbar的item
    func createToolBarItem(){
        
        
        
        //注册可重用cell
        expressionView.registerClass(EomoticonsViewCell.self, forCellWithReuseIdentifier: collectionViewID)
        let array = arrayModel.packages
        var itemArray = [UIBarButtonItem]()
        //创建item
        for  a in 0..<array.count {
            
            let item  = UIBarButtonItem(title: array[a].group_name_cn, style: .Plain, target: self, action: "click:")
            //设置item的tag
            item.tag = a
            
            let itemm = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            //将item添加到数组中
            itemArray.append(item)
            //添加item之间的自动弹簧item
            itemArray.append(itemm)
        }
        
        itemArray.removeLast()
        
        groupTollBar.items = itemArray
        //设置数据
        expressionView.dataSource = self
        expressionView.delegate = self
    }
    
    
    
   @objc private func click(sender: AnyObject?){
        
        //print("我就是\(sender?.title)\(sender?.tag)")
    
        let indexPath = NSIndexPath(forItem: 0, inSection: sender!.tag)
        
        // 滚动 collectionView
        expressionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
        
    }
}

// MARK: - 来实现 collectionview 的数据源方法
extension EmoticonsView: UICollectionViewDelegate, UICollectionViewDataSource{
    
    //实现代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let model = arrayModel.packages[indexPath.section].emoticons[indexPath.item]
        
        selectedEmoticonCallBack(emoticon: model)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return arrayModel.packages.count
    }
    
     func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrayModel.packages[section].emoticons.count
    }
    
     func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewID, forIndexPath: indexPath) as! EomoticonsViewCell
        
        let model = arrayModel.packages[indexPath.section].emoticons[indexPath.item]
        
       // cell.backgroundColor = UIColor.whiteColor()
        
        cell.viewModel = model
        
        return cell
    }
}


///MARK: - collectionView 自定义cell
class EomoticonsViewCell: UICollectionViewCell{
    
    var viewModel: EmoticonsModel?{
        didSet{
            appendButton(viewModel!)
        }
    }
    
    var index = 0
    
    func appendButton(viewModel: EmoticonsModel){
        
        //在这里还需要判断每页只有20个图像
        
        //let but = UIButton(frame: CGRectMake(0, 0, self.bounds.width, self.bounds.height))
        //but.backgroundColor = UIColor.blueColor()
        but.userInteractionEnabled = false
        but.frame = CGRectInset(bounds, 4, 4)
        
        but.addTarget(self, action: "butClick:", forControlEvents: .TouchUpInside)
        //but.setTitle("", forState: .Normal)
        let image = UIImage(named: viewModel.imagePath)
        but.setImage(image, forState: UIControlState.Normal)
        
        but.setTitle(viewModel.emoji, forState: UIControlState.Normal)
        but.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        if viewModel.isRemove == true {
            but.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            // but.setBackgroundImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            but.addTarget(self, action: "removeButClick", forControlEvents: .TouchUpInside)
        }
        contentView.addSubview(but)
    }
    
//    //按钮监听事件
    func butClick(sender:UIButton){
        
        //print(sender.titleLabel?.text)
       NSNotificationCenter.defaultCenter().postNotificationName("click", object: sender)
//        NSNotificationCenter.defaultCenter().postNotificationName("click", object: sender, userInfo: viewMODEL)
        
    }
    
    func removeButClick(){
        
    }
    
    override init(frame:CGRect){
        super.init(frame: frame)
       // tintColor = UIColor.whiteColor()
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var but = UIButton()
    
}


